<template>
  <div class="login-page">
    <img src="../../assets/images/bg_login.png" alt="" class="login-page-bg" />

    <div class="login-page-header">
      <van-nav-bar
        :left-text="$t('返回')"
        left-arrow
        @click-left="onClickLeft"
      />
      <div class="login-page-content">
        <h3>{{ $t('重置密码') }}</h3>
        <van-form @submit="onLoginReset">
          <van-field
            v-model="form.mobile"
            name="mobile"
            :placeholder="$t('请输入手机号')"
            :rules="[{ required: true, message: $t('请输入手机号') }]"
          />
          <van-field
            v-model="form.verifyCode"
            name="verifyCode"
            :placeholder="$t('验证码')"
            :rules="[{ required: true, message: $t('请输入验证码') }]"
          >
            <template #button>
              <van-button
                size="small"
                type="primary"
                @click.prevent="onSendCode"
                class="login-page-valid-code"
                >{{ timedownText || $t('获取验证码') }}</van-button
              >
            </template>
          </van-field>
          <van-field
            v-model="form.newPwd"
            name="newPwd"
            :placeholder="$t('请输入新密码')"
            :rules="[{ required: true, message: $t('请输入新密码') }]"
          />
          <p class="pass-tip">{{ $t('请设置8～20位的数字和字母组合') }}</p>
          <van-field
            v-model="form.affirmPwd"
            name="affirmPwd"
            :placeholder="$t('请再次输入新密码')"
            :rules="[{ required: true, message: $t('请再次输入新密码') }]"
          />
          <div style="margin: 10px">
            <van-button round block type="info" native-type="submit">{{
              $t('重置密码')
            }}</van-button>
          </div>
        </van-form>
      </div>
    </div>
    <ValidImgLayer
      :validImgShow="loginImgShow"
      :phoneNumber="form.mobile"
      :loginNoPhone="false"
      @closeValidImg="onCloseValidImg"
      @validComplete="onValidImgSuccess"
    />
  </div>
</template>
<script>
import { mapMutations } from 'vuex'
import { userService } from '@/services/user'
import globalService from '@/services/globalService'
import ValidImgLayer from '@/components/ValidImgLayer'
import { mapGetters } from 'vuex'
import { Toast } from 'vant'

export default {
  data() {
    return {
      form: {
        mobile: '',
        verifyCode: '',
        newPwd: '',
        affirmPwd: '',
      },
      loginType: 2,
      rules: {
        username: [
          { validator: this.validateUsername, trigger: ['blur', 'change'] },
        ],
        validCode: [
          {
            required: true,
            message: this.$t('验证码不能为空'),
            trigger: ['blur', 'change'],
          },
        ],
      },
      timedownBtnT: null,
      timedownText: '',
      checkedMustRead: false,
      docList: [],
      loginImgShow: false,
      showPopover: false,
      originFrom: localStorage.getItem('originFrom'),
      imageIdentifyCode: '',
    }
  },
  computed: {
    ...mapGetters(['lang']),
    languageOptions() {
      return [
        { text: this.$t('简体中文'), value: 'zh-CN' },
        { text: 'English', value: 'en-US' },
      ]
    },
    currentLanguage() {
      return this.languageOptions.find((c) => c.value === this.lang)?.text
    },
  },
  components: {
    ValidImgLayer,
  },
  methods: {
    ...mapMutations('user', ['SET_TOKEN']),
    onClickLeft() {
      this.$router.go(-1)
    },
    sendSMS() {
      userService
        .sendLoginVerifyCode({
          type: 1,
          mobile: this.form.mobile,
          imageIdentifyCode: this.imageIdentifyCode,
          moduleType: 9,
          firstCheck: 1,
          account: this.form.mobile,
        })
        .then((res) => {
          if (res.code == '200' && res.data.resultCode == '0000') {
            this.onTimedown()
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    validateUsername(rule, value, callback) {
      if (!value) {
        callback(new Error(this.$t('手机号不能为空')))
        return
      }
      if (!/^1\d{10}$/.test(value)) {
        callback(new Error(this.$t('请输入正确的手机号')))
        return
      }
      callback()
    },

    onCloseValidImg() {
      this.loginImgShow = false
    },
    onValidImgSuccess(v) {
      this.imageIdentifyCode = v
      this.loginImgShow = false
      this.sendSMS()
    },
    onTimedown() {
      let t = 60
      this.timedownText = t + this.$t('秒后重新发送')
      this.timedownBtnT = setInterval(() => {
        t = t - 1
        if (t > 0) {
          this.timedownText = t + this.$t('秒后重新发送')
        } else {
          this.timedownText = ''
          clearInterval(this.timedownBtnT)
          this.timedownBtnT = null
        }
      }, 1000)
    },
    onSendCode() {
      if (this.timedownText) {
        return
      }
      if (!this.form.mobile) {
        Toast(this.$t('手机号不能为空'))
        return
      }
      const mobileStr = this.form.mobile
      if (!/^1\d{10}$/.test(mobileStr)) {
        Toast(this.$t('请输入正确的手机号'))
        return
      }
      this.loginImgShow = true
      // userService
      //   .shouldCheckVerifyCode({
      //     account: mobileStr
      //   })
      //   .then((res) => {
      //     if (res.data === 1) {
      //       this.loginImgShow = true
      //       return
      //     }
      //     this.sendSMS()
      //   })
      //   .catch(() => {})
    },
    onLoginReset(values) {
      let reg =
        /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?.,()。、。\*//\-=';:\+"’“\[\]\{\}]+)$)^[\w~!@#$%^&*?.,()。、。\*//\-=';:\+"’“\[\]\{\}]{8,20}$/
      if (!reg.test(this.form.newPwd)) {
        const msg = this.$t('新密码长度应为8~20位的数字和字母组合！')
        Toast(msg)
        return
      }
      if (this.form.affirmPwd !== this.form.newPwd) {
        Toast(this.$t('两次密码不一致'))
        return
      }
      userService
        .updateUserPwd({
          mobile: this.form.mobile,
          verifyCode: this.form.verifyCode,
          newPwd: this.form.newPwd,
          affirmPwd: this.form.affirmPwd,
        })
        .then(({ code }) => {
          if (code == 200) {
            Toast(this.$t('修改成功'))
            this.onClickLeft()
          }
        })
        .catch((err) => {})
    },
  },
  created() {
    localStorage.removeItem('tokenId')
    this.$store.dispatch('user/logout')
  },
}
</script>
<style lang="scss" scoped>
.login-page {
  display: flex;
  font-size: 30px;
  height: 100px;
}

.login-page-lang {
  display: flex;
  justify-content: flex-end;
  font-size: 0.4267rem;
  align-items: center;

  img {
    margin-left: 0.1067rem;
    width: 0.4rem;
    height: 0.4rem;
  }
}

.login-page-bg {
  width: 100%;
  height: 100vh;
}

.login-page-logo {
  width: 300px;
}

.login-page-title {
  font-size: 27px;
  font-weight: bold;
}

.login-page-header {
  z-index: 1;
  position: fixed;
  top: 5vh;
  width: 100%;
  box-sizing: border-box;
  h3 {
    font-size: 22px;
  }
}
.login-page-content {
  padding: 0 26px;
}

.login-page-header-title {
  font-size: 20px;
  font-weight: 600;
}

.van-checkbox {
  display: inline-block;
  margin-right: 10px;
  vertical-align: text-bottom;
}

.checkbox-text {
  font-size: 13px;
  line-height: 20px;
}

.van-button--round {
  background: linear-gradient(270deg, #2457fb 0%, #1b96ff 100%);
  box-shadow: 0px 3px 8px 0px rgba(249, 249, 253, 0.66);
  border-radius: 16px;
  margin-top: 40px;
}

.read-text {
  color: #666666;
}

.van-icon {
  border-radius: 5px;
}

.login-page-valid-code {
  color: #2a54ff;
  background: transparent;
  border: none;
  font-size: 15px;
}
.forget-pass {
  font-weight: 400;
  font-size: 13px;
  color: #888888;
  line-height: 19px;
  text-align: center;
  font-style: normal;
  display: flex;
  justify-content: flex-end;
}
.pass-tip {
  font-size: 12px;
  color: #666666;
  padding-left: 20px;
}
.van-nav-bar {
  background-color: transparent;
  color: #333;
}
</style>
